package mylibrary.activeMQ;

import javax.jms.Connection;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

public class MessageSubscriber implements Runnable{

	private String url;
	private String user;
	private String password;
	private String topicName;
	
	public MessageSubscriber(String url, String user, String password, String topicName) {
		this.url = url;
		this.user = user;
		this.password = password;
		this.topicName = topicName;
	}
	
	public void run() {
	
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(user, password, url);
		
		Session session = null;
		MessageConsumer subscriber = null;
		Connection connection = null;
		
		try {
			
			connection = factory.createConnection();
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			
			Topic topic = session.createTopic(this.topicName);
			
			session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
			
			subscriber = session.createConsumer(topic);
			subscriber.setMessageListener(new TextListener());
			
			connection.start();
			
			System.out.println(Thread.currentThread().getName() + " started!");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getTopicName() {
		return topicName;
	}

	public void setTopicName(String topicName) {
		this.topicName = topicName;
	}
	
}
